<?php

namespace App\Store\Controllers\Alisms;

use App\Store\Models\Alisms\AliSetting;
use App\Store\Models\Alisms\AliTemplate;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Validate\Alisms\AliSetting as ValidateAlismsAliSetting;
use App\Store\Validate\Alisms\AliTemplate as ValidateAlismsAliTemplate;

class AliSettingController extends Controller
{
    public function getalisetting(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = AliSetting::where([['cp_id', $cp_id]])->first();

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    public function postalisetting(Request $request)
    {

        $req_data = $request->only(['access_key_id', 'access_key_secret']);
        $Validate = new ValidateAlismsAliSetting();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = AliSetting::where([['cp_id', $cp_id]])->first();
        $data = $req_data;

        $data['update_at'] = time();
        if ($info) {
            AliSetting::where([['cp_id', $cp_id]])->update($data);
        } else {
            $data['cp_id'] = $cp_id;
            $data['create_at'] = time();
            AliSetting::create($data);
        }
        return response()->json(['code' => '000', 'msg' => '保存配置成功']);
    }

    /**
     * 获取消息模版
     */
    public function getalitemplate(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = AliTemplate::where([['cp_id', $cp_id]])->first();

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    /**
     * 保存消息模版
     */
    public function postalitemplate(Request $request)
    {
        $req_data = $request->only(['phone', 'festival']);
        $Validate = new ValidateAlismsAliTemplate();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = AliTemplate::where([['cp_id', $cp_id]])->first();
        $data = $req_data;

        $data['update_at'] = time();
        if ($info) {
            AliTemplate::where([['cp_id', $cp_id]])->update($data);
        } else {
            $data['cp_id'] = $cp_id;
            $data['create_at'] = time();
            AliTemplate::create($data);
        }
        return response()->json(['code' => '000', 'msg' => '保存配置成功']);
    }
}
